﻿using AuthCenter.Api.Read.Application.Command.Apply;
using AuthCenter.Application;
using AuthCenter.Domain;
using AuthCenter.ErrorCode;
using MediatR;

namespace AuthCenter.Api.Read.Application.Hander.Apply
{
    public class GetApplyHander : IRequestHandler<GetApplyCommand, ApiPaging<ApplyModel>>
    {
        private readonly IBaseRepository<ApplyModel> _applyRepository;
        private readonly IBaseRepository<UserModel> _userRepository;
        public GetApplyHander(IBaseRepository<ApplyModel> applyRepository, IBaseRepository<UserModel> userRepository)
        {
            _applyRepository = applyRepository;
            _userRepository = userRepository;
        }
        /// <summary>
        /// 显示申请列表
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public Task<ApiPaging<ApplyModel>> Handle(GetApplyCommand request, CancellationToken cancellationToken)
        {
            ApiPaging<ApplyModel> res = new ApiPaging<ApplyModel>();
            var model = _applyRepository.GetAll().Where(x => x.IsDeleted == false);
            var login = _userRepository.GetAll().Where(x => x.UserName == request.LoginName).FirstOrDefault();
            var list=new List<ApplyModel>();
            if (login.IsDepartmentName == true)
            {
                list = _applyRepository.GetAll().Where(x => x.IsDeleted == false && x.departmentId == login.DepartmentId).ToList();
                 
            }
            else 
            {
                list = _applyRepository.GetAll().Where(x => x.IsDeleted == false && x.UserName == request.LoginName).ToList();
                
            }


            if (!string.IsNullOrEmpty(request.Status))
            {
                list = model.Where(x => x.Status == request.Status).ToList();
            }
            if (!string.IsNullOrEmpty(request.UserName))
            {
                list = model.Where(x => x.UserName.Contains(request.UserName)).ToList();
            }
            if (request.STime != null && request.ETime != null)
            {
                list = model.Where(x => x.CreateTime >= request.STime && x.CreateTime <= request.ETime.Value.AddDays(1)).ToList();
            }
            res.TotalCount = list.Count();
            res.PageDatas = list.OrderByDescending(x => x.Id).Skip((request.PageIndex - 1) * request.PageSize).Take(request.PageSize).ToList();
            res.Code = ApiEnums.OK;
            res.Message = "获取申请列表";
            return Task.FromResult(res);




        }
    }
}
